const arr = [
    { id: 2, pid: 1 },
    { id: 3, pid: 1 },
    { id: 4, pid: 2 },
    { id: 1, pid: 0 },
    { id: 5, pid: 2 },
    { id: 6, pid: 3 },
];

function arr2tree(arr) {
    const hash = {};
    const result = [];

    for (let item of arr) {
        hash[item.id] = item;
    }

    for (let item of arr) {
        const parent = hash[item.pid];

        if (parent) {
            if (!parent.children) {
                parent.children = [];
            }
            parent.children.push(item);
        } else {
            result.push(item);
        }
    }

    return result;
}

const result = arr2tree(arr);
console.log(JSON.stringify(result, null, 4));

/*
function arrayToTree(list) {
    const result = [];
    // 存放结果集
    const map = {};

    for (const item of list) {
        const id = item.id;
        const pid = item.pid;
        //把当前值加入map
        if (!map[id]) {
            map[id] = { children: [] };
        }
        map[id] = { ...item, children: map[id]['children'] };
        const treeItem = map[id];
        if (pid === 0) {
            result.push(treeItem);
        } else {
            if (!map[pid]) {
                map[pid] = { children: [] };
            }
            map[pid].children.push(treeItem);
        }
    }
    return result;
}
*/
